package com.newshub.app.ui.category

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.newshub.app.R
import com.newshub.app.databinding.FragmentCategoryBinding

class CategoryFragment : Fragment() {
    
    private var _binding: FragmentCategoryBinding? = null
    private val binding get() = _binding!!
    
    private lateinit var categoryPagerAdapter: CategoryPagerAdapter
    
    // 新闻分类列表
    private val categories = arrayOf(
        "推荐", "科技", "财经", "体育", "娱乐", "健康", "教育", "汽车"
    )
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentCategoryBinding.inflate(inflater, container, false)
        return binding.root
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        setupViewPager()
        setupTabLayout()
    }
    
    private fun setupViewPager() {
        categoryPagerAdapter = CategoryPagerAdapter(requireActivity())
        binding.viewPager.adapter = categoryPagerAdapter
    }
    
    private fun setupTabLayout() {
        TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
            tab.text = categories[position]
        }.attach()
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
    
    // ViewPager适配器
    inner class CategoryPagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) {
        
        override fun getItemCount(): Int {
            return categories.size
        }
        
        override fun createFragment(position: Int): Fragment {
            return CategoryNewsFragment.newInstance(categories[position])
        }
    }
}